package com.nerve.cloudoffice.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.nerve.util.FormatUtil;

import com.nerve.cloudoffice.common.SessionUtil;
import com.nerve.cloudoffice.common.util.Md5;
import com.nerve.cloudoffice.domain.Department;
import com.nerve.cloudoffice.domain.User;
import com.nerve.cloudoffice.domain.dao.DepartmentDao;
import com.nerve.cloudoffice.domain.dao.NotifyDao;
import com.nerve.cloudoffice.domain.dao.TaskDao;
import com.nerve.cloudoffice.domain.dao.TrashApplyDao;
import com.nerve.cloudoffice.domain.dao.UserDao;
import com.nerve.cloudoffice.service.ServiceExceptions;
import com.nerve.cloudoffice.service.UserService;
import com.nerve.cloudoffice.web.model.IndexModel;
import com.nerve.cloudoffice.web.model.UserModel;

/**
 * @project cloudOffice UserServiceImpl.java
 * @datetime Aug 1, 2013 10:18:38 PM
 * @description 
 * 	userService的实现类   
 * @author 集成显卡 IBM 
 *			zxingming@qq.com
 *			zengxm@cn.ibm.com
 *
 * @change log:
 *
 */
public final class UserServiceImpl implements UserService {

	private UserDao dao;
	private DepartmentDao departmentDao;
	private TaskDao taskDao;
	private NotifyDao notifyDao;
	private TrashApplyDao trashDao;
	
	private TaskDao getTaskDao(){
		if(taskDao == null)
			taskDao = new TaskDao();
		
		return taskDao;
	}
	
	private NotifyDao getNotifyDao(){
		if(notifyDao == null)
			notifyDao = new NotifyDao();
		
		return notifyDao;
	}
	
	private UserDao getDao(){
		if(dao == null)
			dao = new UserDao();
		
		return dao;
	}
	
	private TrashApplyDao getTrashDao(){
		if(trashDao == null)
			trashDao = new TrashApplyDao();
		
		return trashDao;
	}
	
	private DepartmentDao getDepartmentDao(){
		if(departmentDao == null)
			departmentDao = new DepartmentDao();
		
		return departmentDao;
	}
	
	public void list(UserModel model) throws Exception {
		StringBuilder hql = new StringBuilder("FROM User WHERE unable=0");
		
		if(model.getDid() > 0){
			hql.append(" and department_id=" + model.getDid());
		}
		if(model.getKey() != null){
			String key = new String(model.getKey().getBytes("ISO-8859-1"),"utf-8");
			hql.append(" and name like '%" + key + "%'");
		}
		
		model.setTotalCount(getDao().countRow(hql.toString()));
		System.out.println("total size:" + model.getTotalCount());
		List<User> list = getDao().getList(hql.toString(), model.getPage(), model.getPageSize());
		model.setUserList(list);
	}

	public void save(UserModel model) throws Exception {
		User user  = model.getUser();
		
		FormatUtil.notNull(user, "填写的参数有误！");
		FormatUtil.notNull(user.getName(), "职员姓名不能为空！");
		FormatUtil.notNull(user.getPassword(), "登录密码不能为空！");
		
		System.out.println(model.getDid() + user.getName());
		Department d = getDepartmentDao().getById(model.getDid());
		FormatUtil.notNull(d, "所在部门没有选择！");
		
		user.setDepartment(d);
		user.setPassword(Md5.Encrypt(user.getPassword()));//对密码加密
		user.setJoinDate(new Date());
		
		//随机生成一个头像
		Random random = new Random();
		String header = (user.getSex() == 0?"man_":"woman_")+random.nextInt(12);
		user.setHeader(header);
		
		getDao().save(user);
	}

	public void update(UserModel model) throws Exception {
		User u = getDao().getById(model.getId());
		
		if(u == null)
			throw new RuntimeException("无效的职员对象！");
		
		if(model.getUpdateType() != UNABLE && model.getUpdateValue() == null){
			throw new RuntimeException(ServiceExceptions.NOT_UPDATE_VALUE);
		}

		int intValue;
		switch (model.getUpdateType()) {
		case PASSWORD:
			u.setPassword(Md5.Encrypt(model.getUpdateValue()));
			break;
		case POSITION:
			intValue = Integer.valueOf(model.getUpdateValue());
			u.setPosition(intValue);
			break;
		case DEPARTMENT:
			intValue = Integer.valueOf(model.getUpdateValue());
			Department d = getDepartmentDao().getById(intValue);
			
			u.setDepartment(d);
			break;
		//这个只是切换
		case UNABLE:
			u.setUnable(!u.isUnable());
			break;
			
		case CELLPHONE:
			u.setCellPhone(model.getUpdateValue());
			break;
		}
		
		getDao().update(u);
	}

	public User login(String name, String pass) throws Exception {
		User u = getDao().getByInfo("name", name, "password", Md5.Encrypt(pass));
		return u;
	}

	public Map<String, Integer> countNotify(IndexModel model) throws Exception {
		Map<String, Integer> map = new HashMap<String, Integer>();
		
		User u = SessionUtil.getLoginUser();
		
		int notifySize = getNotifyDao().
				countRow("FROM Notify as n WHERE n.id > "+model.getLastNotifyId());
		int taskSize = getTaskDao().
				countRow("FROM Task as t WHERE t.status < 100 and t.workUser.id=" + u.getId());
		
		int trashSize = 0;
		if(u.getPosition() != User.EMPLOYEE){
			StringBuilder hql = new StringBuilder("FROM TrashApply as t WHERE t.agree=0");
			if(u.getPosition() == User.HEAD_OF_DEPARTMENT){
				int did = u.getDepartment().getId();
				
				hql.append(" and t.sender.department.id=" + did);
			}
			getTrashDao().countRow(hql.toString());
		}
		
		map.put("notify", notifySize);
		map.put("task", taskSize);
		map.put("trashApply", trashSize);
		
		return map;
	}

	public void updateBatch(UserModel model) throws Exception {
		User u = getDao().getById(SessionUtil.getLoginUser().getId());
		
		User modelU = model.getUser();
		u.setAddress(modelU.getAddress());
		u.setBirthday(modelU.getBirthday());
		u.setCellPhone(modelU.getCellPhone());
		u.setHeader(modelU.getHeader());
		u.setSign(modelU.getSign());
		
		getDao().merge(u);
	}

}